<template>
  <div class="space-y-6" style="background-color: #FAF9F5; min-height: 100vh; padding: 1.5rem;">
    <!-- 页面标题 -->
    <div class="rounded-[0.6rem] p-6" style="background-color: #FAF9F5; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);">
      <h1 class="text-2xl font-bold text-gray-900 mb-2">宿舍申请</h1>
      <p class="text-gray-600">选择合适的宿舍，开启美好的校园生活</p>
    </div>

    <!-- 申请状态 -->
    <div class="rounded-[0.6rem] p-6" style="background-color: #FAF9F5; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);">
      <div class="flex items-center justify-between mb-4">
        <h2 class="text-lg font-semibold text-gray-900">申请状态</h2>
        <span
          class="px-3 py-1 text-sm font-medium rounded-full"
          :class="[
            applicationStatus === 'approved' ? 'bg-green-100 text-green-800' :
            applicationStatus === 'pending' ? 'bg-yellow-100 text-yellow-800' :
            applicationStatus === 'rejected' ? 'bg-red-100 text-red-800' :
            'bg-gray-100 text-gray-800'
          ]"
        >
          {{ getStatusText(applicationStatus) }}
        </span>
      </div>
      
      <div v-if="currentApplication" class="space-y-3">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <span class="text-sm text-gray-500">申请宿舍</span>
            <p class="font-medium">{{ currentApplication.buildingName }} {{ currentApplication.roomNumber }}室</p>
          </div>
          <div>
            <span class="text-sm text-gray-500">申请时间</span>
            <p class="font-medium">{{ formatDate(currentApplication.appliedAt) }}</p>
          </div>
        </div>
        
        <div v-if="applicationStatus === 'approved'" class="mt-4 p-4 bg-green-50 rounded-lg">
          <div class="flex items-start space-x-3">
            <i class="icon-[heroicons--check-circle] w-5 h-5 text-green-600 mt-0.5"></i>
            <div>
              <h3 class="text-sm font-medium text-green-800">申请已通过</h3>
              <p class="text-sm text-green-700 mt-1">恭喜！您的宿舍申请已通过审核，请按时入住。</p>
            </div>
          </div>
        </div>
      </div>
      
      <div v-else class="text-center py-8">
        <i class="icon-[heroicons--home] w-12 h-12 text-gray-400 mx-auto mb-4"></i>
        <p class="text-gray-500">您还没有申请宿舍</p>
      </div>
    </div>

    <!-- 宿舍楼列表 -->
    <div v-if="!currentApplication || applicationStatus === 'none'" class="rounded-[0.6rem] p-6" style="background-color: #FAF9F5; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);">
      <h2 class="text-lg font-semibold text-gray-900 mb-6">选择宿舍楼</h2>
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div
          v-for="building in dormitoryBuildings"
          :key="building.id"
          class="border border-gray-200 rounded-[0.6rem] p-4 hover:border-blue-300 transition-all duration-200 cursor-pointer active:scale-[0.985]"
          :class="{ 'border-blue-500': selectedBuilding?.id === building.id }"
          :style="selectedBuilding?.id === building.id ? 'background-color: #EBF8FF; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);' : 'background-color: #F5F5F0; box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.06);'"
          @click="selectBuilding(building)"
        >
          <div class="flex items-start justify-between mb-3">
            <h3 class="font-semibold text-gray-900">{{ building.name }}</h3>
            <span
              class="px-2 py-1 text-xs font-medium rounded-full"
              :class="[
                building.availableRooms > 0 ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
              ]"
            >
              {{ building.availableRooms > 0 ? '有空房' : '已满' }}
            </span>
          </div>
          
          <div class="space-y-2 text-sm text-gray-600">
            <div class="flex items-center space-x-2">
              <i class="icon-[heroicons--users] w-4 h-4"></i>
              <span>{{ building.roomType }}</span>
            </div>
            <div class="flex items-center space-x-2">
              <i class="icon-[heroicons--currency-yen] w-4 h-4"></i>
              <span>{{ building.price }}元/年</span>
            </div>
            <div class="flex items-center space-x-2">
              <i class="icon-[heroicons--map-pin] w-4 h-4"></i>
              <span>{{ building.location }}</span>
            </div>
            <div class="flex items-center space-x-2">
              <i class="icon-[heroicons--home] w-4 h-4"></i>
              <span>剩余 {{ building.availableRooms }} 间</span>
            </div>
          </div>
          
          <div class="mt-3">
            <div class="text-xs text-gray-500 mb-1">设施</div>
            <div class="flex flex-wrap gap-1">
              <span
                v-for="facility in building.facilities"
                :key="facility"
                class="px-2 py-0.5 bg-gray-100 text-gray-600 text-xs rounded"
              >
                {{ facility }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 房间选择 -->
    <div v-if="selectedBuilding && (!currentApplication || applicationStatus === 'none')" class="rounded-[0.6rem] p-6" style="background-color: #FAF9F5; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);">
      <h2 class="text-lg font-semibold text-gray-900 mb-6">选择房间 - {{ selectedBuilding.name }}</h2>
      <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
        <div
          v-for="room in availableRooms"
          :key="room.id"
          class="border border-gray-200 rounded-[0.6rem] p-3 text-center cursor-pointer hover:border-blue-300 transition-all duration-200 active:scale-[0.985]"
          :class="{
            'border-blue-500': selectedRoom?.id === room.id,
            'border-gray-300 cursor-not-allowed': room.occupied >= room.capacity
          }"
          :style="selectedRoom?.id === room.id ? 'background-color: #EBF8FF; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);' : room.occupied >= room.capacity ? 'background-color: #F9FAFB; box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.06);' : 'background-color: #F5F5F0; box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.06);'"
          @click="selectRoom(room)"
        >
          <div class="font-medium text-gray-900">{{ room.number }}室</div>
          <div class="text-sm text-gray-600 mt-1">
            {{ room.occupied }}/{{ room.capacity }}人
          </div>
          <div class="text-xs text-gray-500 mt-1">
            {{ room.occupied >= room.capacity ? '已满' : '可选' }}
          </div>
        </div>
      </div>
    </div>

    <!-- 室友信息 -->
    <div v-if="selectedRoom && selectedRoom.roommates.length > 0" class="rounded-[0.6rem] p-6" style="background-color: #FAF9F5; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);">
      <h2 class="text-lg font-semibold text-gray-900 mb-4">室友信息</h2>
      <div class="space-y-3">
        <div
          v-for="roommate in selectedRoom.roommates"
          :key="roommate.id"
          class="flex items-center space-x-3 p-3 border border-gray-200 rounded-[0.6rem]"
          style="background-color: #F5F5F0; box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
        >
          <div class="w-10 h-10 bg-blue-500 rounded-full flex items-center justify-center">
            <i class="icon-[heroicons--user] w-5 h-5 text-white"></i>
          </div>
          <div class="flex-1">
            <p class="font-medium text-gray-900">{{ roommate.name }}</p>
            <p class="text-sm text-gray-600">{{ roommate.major }} · {{ roommate.class }}</p>
          </div>
          <div class="text-sm text-gray-500">
            {{ roommate.hometown }}
          </div>
        </div>
      </div>
    </div>

    <!-- 申请按钮 -->
    <div v-if="selectedRoom && (!currentApplication || applicationStatus === 'none')" class="rounded-[0.6rem] p-6" style="background-color: #FAF9F5; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);">
      <div class="flex items-center justify-between">
        <div>
          <h3 class="font-semibold text-gray-900">确认申请</h3>
          <p class="text-sm text-gray-600 mt-1">
            {{ selectedBuilding.name }} {{ selectedRoom.number }}室 - {{ selectedBuilding.price }}元/年
          </p>
        </div>
        <button
          @click="submitApplication"
          :disabled="submitting"
          class="px-6 py-2 text-white font-medium border border-blue-600 rounded-[0.6rem] hover:border-blue-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 active:scale-[0.985]"
          style="background-color: #3B82F6; box-shadow: 0 2px 4px -1px rgba(0, 0, 0, 0.06);"
        >
          {{ submitting ? '提交中...' : '提交申请' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useAppStore } from '../../stores/app'

const appStore = useAppStore()

// 响应式数据
const applicationStatus = ref('none') // none, pending, approved, rejected
const currentApplication = ref(null)
const selectedBuilding = ref(null)
const selectedRoom = ref(null)
const submitting = ref(false)

// 宿舍楼数据
const dormitoryBuildings = ref([
  {
    id: 1,
    name: '梧桐苑1号楼',
    roomType: '4人间',
    price: 1200,
    location: '校园东区',
    availableRooms: 15,
    facilities: ['空调', '独立卫浴', '阳台', '网络']
  },
  {
    id: 2,
    name: '梧桐苑2号楼',
    roomType: '4人间',
    price: 1200,
    location: '校园东区',
    availableRooms: 8,
    facilities: ['空调', '独立卫浴', '阳台', '网络']
  },
  {
    id: 3,
    name: '银杏苑1号楼',
    roomType: '6人间',
    price: 800,
    location: '校园西区',
    availableRooms: 23,
    facilities: ['空调', '公共卫浴', '网络']
  },
  {
    id: 4,
    name: '银杏苑2号楼',
    roomType: '6人间',
    price: 800,
    location: '校园西区',
    availableRooms: 0,
    facilities: ['空调', '公共卫浴', '网络']
  }
])

// 可用房间数据
const availableRooms = ref([])

// 计算属性
const getStatusText = (status) => {
  const statusMap = {
    none: '未申请',
    pending: '审核中',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return statusMap[status] || '未知'
}

// 方法
const selectBuilding = (building) => {
  if (building.availableRooms === 0) {
    appStore.showWarning('该宿舍楼已满，请选择其他宿舍楼')
    return
  }
  
  selectedBuilding.value = building
  selectedRoom.value = null
  loadAvailableRooms(building.id)
}

const selectRoom = (room) => {
  if (room.occupied >= room.capacity) {
    appStore.showWarning('该房间已满，请选择其他房间')
    return
  }
  
  selectedRoom.value = room
}

const loadAvailableRooms = (buildingId) => {
  // 模拟加载房间数据
  const mockRooms = []
  for (let i = 101; i <= 120; i++) {
    const occupied = Math.floor(Math.random() * 5)
    const capacity = selectedBuilding.value.roomType === '4人间' ? 4 : 6
    
    mockRooms.push({
      id: i,
      number: i,
      occupied: Math.min(occupied, capacity),
      capacity,
      roommates: generateRoommates(Math.min(occupied, capacity))
    })
  }
  
  availableRooms.value = mockRooms
}

const generateRoommates = (count) => {
  const names = ['李明', '王小红', '张伟', '刘芳', '陈强']
  const majors = ['计算机科学', '电子工程', '机械工程', '经济学', '英语']
  const classes = ['1班', '2班', '3班', '4班', '5班']
  const hometowns = ['北京', '上海', '广州', '深圳', '杭州', '南京', '成都']
  
  const roommates = []
  for (let i = 0; i < count; i++) {
    roommates.push({
      id: i + 1,
      name: names[Math.floor(Math.random() * names.length)],
      major: majors[Math.floor(Math.random() * majors.length)],
      class: classes[Math.floor(Math.random() * classes.length)],
      hometown: hometowns[Math.floor(Math.random() * hometowns.length)]
    })
  }
  
  return roommates
}

const submitApplication = async () => {
  if (!selectedBuilding.value || !selectedRoom.value) {
    appStore.showWarning('请选择宿舍和房间')
    return
  }
  
  submitting.value = true
  
  try {
    // 模拟提交申请
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    currentApplication.value = {
      buildingName: selectedBuilding.value.name,
      roomNumber: selectedRoom.value.number,
      appliedAt: new Date().toISOString()
    }
    
    applicationStatus.value = 'pending'
    selectedBuilding.value = null
    selectedRoom.value = null
    
    appStore.showSuccess('宿舍申请提交成功，请等待审核')
  } catch (error) {
    appStore.showError('申请提交失败，请重试')
  } finally {
    submitting.value = false
  }
}

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  appStore.setPageTitle('宿舍申请')
  
  // 模拟已有申请状态
  // applicationStatus.value = 'approved'
  // currentApplication.value = {
  //   buildingName: '梧桐苑1号楼',
  //   roomNumber: '101',
  //   appliedAt: '2024-08-15T10:30:00.000Z'
  // }
})
</script>

<style scoped>
/* 自定义样式 */
</style>